package com.example.springstack.springsecurity.utils;

import com.exampl.springstack.common.exceptionUtils.enums.ResultEnum;
import com.exampl.springstack.common.exceptionUtils.exception.SystemException;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author qiangfanghao
 * @date
 * 用户认证信息获取类
 * 获取当前用户信息
 */
@Slf4j
public class SecurityUtils {

    /**
     * 获取系统用户名称
     * @return 系统用户名称
     */
    public static String getUsername(){
        UserDetails userDetails = getUserDetails();
        return userDetails.getUsername();
    }

    /**
     * 获取登录用户详情信息
     * @return
     */
    public static UserDetails getUserDetails() {
        UserDetails userDetails = null;
        try {
            userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            log.error("【SecurityUtils:getUserDetails】获取用户信息失败={}", e.getMessage(), e);
            throw new SystemException(ResultEnum.DATA_ERROR_PARAM);
        }
        return userDetails;
    }

}
